<template>
  <Dialog v-model="dialogVisible" title="合并客户" width="800">
    <el-scrollbar height="600px" :always="true">
      <div style="display: flex">
        <div class="first-column">
          <span class="ellipsis" style="position: sticky; top: 0; background-color: #f2f2f2">
            <el-text style="color: 409eff">合并结果</el-text>
          </span>
          <span class="ellipsis" v-for="(column, index) in firstColumnData" :key="index">
            <el-text :style="{ color: column.color }">{{ column.showName }}</el-text>
            <span class="ellipsis">{{ mergeCustomerInfo[column.fieldName] }}</span>
          </span>
        </div>
        <div style="display: grid; align-content: center">
          <div class="header">
            <el-radio-group
              v-model="allRadioId"
              style="white-space: nowrap"
              @change="allRadioChange"
            >
              <el-radio v-for="customerId in allRadioIds" :key="customerId" :value="customerId">
                全选
              </el-radio>
            </el-radio-group>
          </div>
          <div style="height: 40px" v-for="(customerInfo, index) in radioInfos" :key="index">
            <el-radio-group v-model="radioData[index]" style="white-space: nowrap">
              <el-radio
                v-for="field in customerInfo"
                :key="field.customerId"
                :value="field.customerId"
              >
                {{ field.label }}
              </el-radio>
            </el-radio-group>
          </div>
        </div>
      </div>
    </el-scrollbar>
    <template #footer>
      <el-button type="primary" @click="submitForm">合并</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup name="CustomerMerge" lang="ts">
import * as CustomerCheckApi from '@/api/customer/customerCheck'
import { SettingBusinessModuleEnum } from '@/utils/constants'
import { getBussinessModule } from '@/views/setting/businessField/BusinessFieldUtil'
import { getKeyList } from '@pureadmin/utils'
import { cloneDeep } from 'lodash-es'
const message = useMessage() // 消息弹窗
const dialogVisible = ref(false)
const mergeCustomerInfo = ref()
const customerInfos = ref<any>()
const firstColumnData = ref()

const radioInfos = ref<any>({})
const radioData = ref<any>({})
const allRadioIds = ref<any[]>()
const allRadioId = ref()
const customerModuleField = ref()

const open = async (customerRows) => {
  firstColumnData.value = [
    {
      color: 'red',
      fieldName: 'customerNo',
      showName: '客户编号：'
    },
    {
      color: 'red',
      fieldName: 'name',
      showName: '名称：'
    },
    {
      color: 'red',
      fieldName: 'shortName',
      showName: '简称：'
    },
    {
      color: 'red',
      fieldName: 'ownerIdShowName',
      showName: '所属人：'
    },
    {
      color: 'red',
      fieldName: 'deptIdShowName',
      showName: '所属部门：'
    }
  ]
  radioInfos.value = {}
  radioData.value = {}
  customerInfos.value = {}
  allRadioIds.value = getKeyList(customerRows, 'id')
  allRadioId.value = allRadioIds.value[0]
  customerRows.forEach((row) => {
    row.ownerIdShowName = row.owner?.nickname
    row.deptIdShowName = row.dept?.name
    customerInfos.value[row.id] = row
    radioInfos.value['customerNo'] ??= []
    radioInfos.value['customerNo'].push({
      customerId: row.id,
      value: row.customerNo,
      label: row.customerNo
    })
    radioInfos.value['name'] ??= []
    radioInfos.value['name'].push({ customerId: row.id, value: row.name, label: row.name })
    radioInfos.value['shortName'] ??= []
    radioInfos.value['shortName'].push({
      customerId: row.id,
      value: row.shortName,
      label: row.shortName
    })
    radioInfos.value['ownerId'] ??= []
    radioInfos.value['ownerId'].push({
      customerId: row.id,
      value: row.ownerId,
      label: row.owner?.nickname
    })
    radioInfos.value['deptId'] ??= []
    radioInfos.value['deptId'].push({
      customerId: row.id,
      value: row.deptId,
      label: row.dept?.name
    })
  })

  mergeCustomerInfo.value = cloneDeep(customerRows[0])
  radioData.value = {
    customerNo: mergeCustomerInfo.value.id,
    name: mergeCustomerInfo.value.id,
    shortName: mergeCustomerInfo.value.id,
    ownerId: mergeCustomerInfo.value.id,
    deptId: mergeCustomerInfo.value.id
  }
  // 加载业务字段
  customerModuleField.value = await getBussinessModule(SettingBusinessModuleEnum.CUSTOMER)
  customerModuleField.value.immutableFields.forEach((item) => {
    mergeCustomerInfo.value[item.fieldName + 'ShowName'] =
      mergeCustomerInfo.value[item.fieldName] == 0
        ? ''
        : item.options.find((obj) => obj.id === mergeCustomerInfo.value[item.fieldName])?.name
    firstColumnData.value.push({
      color: 'red',
      fieldName: item.fieldName + 'ShowName',
      showName: item.showName + '：'
    })
    customerRows.forEach((row) => {
      radioInfos.value[item.fieldName] ??= []
      radioInfos.value[item.fieldName].push({
        customerId: row.id,
        value: row[item.fieldName],
        label:
          row[item.fieldName] == 0
            ? ''
            : item.options.find((obj) => obj.id === row[item.fieldName])?.name
      })
    })
    radioData.value[item.fieldName] = mergeCustomerInfo.value.id
  })
  customerModuleField.value.customFields.forEach((item) => {
    firstColumnData.value.push({
      color: 'none',
      fieldName: item.fieldName,
      showName: item.showName + '：'
    })
    customerRows.forEach((row) => {
      radioInfos.value[item.fieldName] ??= []
      radioInfos.value[item.fieldName].push({
        customerId: row.id,
        value: row[item.fieldName],
        label: row[item.fieldName]
      })
    })
    radioData.value[item.fieldName] = mergeCustomerInfo.value.id
  })

  dialogVisible.value = true
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

watch(
  () => radioData,
  (newRadioCustomerData) => {
    Object.entries(newRadioCustomerData.value).forEach(([key, value]) => {
      if (customerInfos.value != undefined) {
        mergeCustomerInfo.value[key] = customerInfos.value[value as string][key]
        mergeCustomerInfo.value['deptIdShowName'] = customerInfos.value[value as string].dept.name
        mergeCustomerInfo.value['ownerIdShowName'] =
          customerInfos.value[value as string].owner.nickname

        if (customerModuleField.value != undefined) {
          customerModuleField.value.immutableFields.forEach((item) => {
            mergeCustomerInfo.value[item.fieldName + 'ShowName'] =
              mergeCustomerInfo.value[item.fieldName] == 0
                ? ''
                : item.options.find((obj) => obj.id === mergeCustomerInfo.value[item.fieldName])
                    ?.name
          })
        }
      }
    })
  },
  { deep: true }
)

const emit = defineEmits(['success'])
const allRadioChange = () => {
  Object.entries(radioData.value).forEach(([key]) => {
    radioData.value[key] = allRadioId.value
  })
}

const submitForm = async () => {
  mergeCustomerInfo.value['ids'] = allRadioIds
  await CustomerCheckApi.merge(mergeCustomerInfo.value)
  message.success('合并成功')
  dialogVisible.value = false
  emit('success')
}
</script>
<style scoped>
.first-column {
  position: sticky;
  left: 0;
  background-color: #f2f2f2;
  display: grid;
  z-index: 12;
}
.first-column > span {
  width: 250px;
  height: 40px;
  display: flex;
  align-items: center;
  padding: 0 10px;
  border-left: 1px solid #e4e4e4;
  border-bottom: 1px solid #e4e4e4;
}
.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.header {
  position: sticky;
  top: 0;
  z-index: 10;
  border-top: 1px solid #e4e4e4;
  background-color: #ffffff;
  height: 40px;
}
.el-radio-group {
  flex-wrap: nowrap;
}
.el-radio {
  width: 250px;
  height: 40px;
  border-left: 1px solid #e4e4e4;
  border-bottom: 1px solid #e4e4e4;
  justify-content: center;
  margin-right: 0;
}

:deep(.el-scrollbar__bar) {
  z-index: 100;
}
</style>
